<?php
  include("DBConfig.class.php");
  class District{

    public function getDistrict($value){

      //Query Province
      try {
        $db = new PDO("mysql:host=".DBConfig::$dbhost.";dbname=".DBConfig::$dbname, 
                      DBConfig::$dbuser, 
                      DBConfig::$dbpass, 
                      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
                  );
        $db->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

        $value['pro'] = urldecode($value['pro']);
        $sql = "SELECT ".
                  $value['filter'].",
                  province,
                  province_lat,
                  province_lon 
                FROM ".DBConfig::$dbfieldname."
                WHERE province = :where
                GROUP BY ".$value['filter']."
                ORDER BY id ASC";
        $stmt = $db->prepare($sql);
        $stmt->bindParam( ':where', $value['pro'], PDO::PARAM_STR );

        $stmt->execute();
        $result = $stmt->fetchAll();

        if(!empty($result)){
          $response['votename'] = $value['votename'];
          $response['country'] = $value['country'];
          $response['layer'] = $result;
          $response['errorCode'] = 0;
          $response['errorString'] = "ok";
          $this->setDistrictResponse($response);
        } else{
          $response['errorCode'] = 102;
          $response['errorString'] = "District not found.";
          $this->setDistrictResponse($response);
        }

        /*** close the database connection ***/
        $db = null;
      }catch(PDOException $e) {
          //echo $e->getMessage();
          $response['errorCode'] = 5;
          $response['errorString'] = "Database cann't connect";
          $this->setDistrictResponse($response);
      }
    }

    public function searchDistrict($value){

      //Query Province
      try {
        $db = new PDO("mysql:host=".DBConfig::$dbhost.";dbname=".DBConfig::$dbname, 
                      DBConfig::$dbuser, 
                      DBConfig::$dbpass, 
                      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
                  );
        $db->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

        $sql = "SELECT ".
                  $value['filter'].",
                  province,
                  province_lat,
                  province_lon 
                FROM ".DBConfig::$dbfieldname."
                WHERE ".$value['filter']." like '%".$value['key']."%'
                GROUP BY ".$value['filter']."
                ORDER BY id ASC";
        $stmt = $db->prepare($sql);

        $stmt->execute();
        $result = $stmt->fetchAll();

        if(!empty($result)){
          $response['votename'] = $value['votename'];
          $response['country'] = $value['country'];
          $response['layer'] = $result;
          $response['errorCode'] = 0;
          $response['errorString'] = "ok";
          $this->setDistrictSearchResponse($response);
        } else{
          $response['errorCode'] = 102;
          $response['errorString'] = "District not found.";
          $this->setDistrictSearchResponse($response);
        }

        /*** close the database connection ***/
        $db = null;
      }catch(PDOException $e) {
          //echo $e->getMessage();
          $response['errorCode'] = 5;
          $response['errorString'] = "Database cann't connect";
          $this->setDistrictSearchResponse($response);
      }
    }

    public function setDistrictResponse($response){

        //Gen food
        $xml = new DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;

        $xml_node_datas = $xml->createElement("Datas");
        $xml->appendChild( $xml_node_datas);

        if($response['errorCode'] == 0){

          $xml_node_country = $xml->createElement("country",$response['country']);
          $xml_node_datas->appendChild( $xml_node_country);

          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );


          //Check thai country 
          if($response['country'] == "TH"){
            $string = "จังหวัด";
            if(strstr($response['layer'][0]['province'],$string)){
              $title = "สถานที่ตั้ง".$response['layer'][0]['province'];
              $address = $response['layer'][0]['province'];
            }else{
              $title = "สถานที่ตั้งจังหวัด".$response['layer'][0]['province'];
              $address =  "จังหวัด".$response['layer'][0]['province'];
            }
          }else{
            $title = $response['layer'][0]['province']." location ";
            $address = $response['layer'][0]['province'];
          }

          $xml_node_data = $xml->createElement("Data");
          $xml_node_data->setAttribute("id", 1);
          $xml_node_datas->appendChild( $xml_node_data);

          $xml_node_type = $xml->createElement("type","map");
          $xml_node_data->appendChild( $xml_node_type);

          $xml_node_title = $xml->createElement("title",$title);
          $xml_node_data->appendChild( $xml_node_title);

          $xml_node_address = $xml->createElement("address",$address);
          $xml_node_data->appendChild( $xml_node_address);

          $xml_node_lat = $xml->createElement("latitude",$response['layer'][0]['province_lat']);
          $xml_node_data->appendChild( $xml_node_lat);

          $xml_node_lon = $xml->createElement("longitude",$response['layer'][0]['province_lon']);
          $xml_node_data->appendChild( $xml_node_lon);
          $count = 2;
          foreach($response['layer'] as $val){

            $xml_node_data = $xml->createElement("Data");
            $xml_node_data->setAttribute("id", $count++);
            $xml_node_datas->appendChild( $xml_node_data);


            $xml_node_type = $xml->createElement("type","list");
            $xml_node_data->appendChild( $xml_node_type);

            //Check thai country 
            if($response['country'] == "TH"){
              $string = "อำเภอ";
              if(strstr($val['district'],$string)){
                $district = $val['district'];
              }else{
                $district = "อำเภอ".$val['district'];
              }
            }else{
              $district = $val['district'];
            }

            $xml_node_title = $xml->createElement("title", $district);
            $xml_node_data->appendChild( $xml_node_title);

            $arg = array(
                          'pro' => $val['province'],
                          'dis' => $val['district']
                        );
            $xml_node_xml = $xml->createElement("xml", htmlentities($this->getNextURL("district", "tambon", $arg)));
            $xml_node_data->appendChild( $xml_node_xml);

          }
        }else{
          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );
        }

        echo $xml->saveXML();
    }

    public function setDistrictSearchResponse($response){

        //Gen food
        $xml = new DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;

        $xml_node_datas = $xml->createElement("Datas");
        $xml->appendChild( $xml_node_datas);

        if($response['errorCode'] == 0){

          $xml_node_country = $xml->createElement("country",$response['country']);
          $xml_node_datas->appendChild( $xml_node_country);

          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );

          $count = 1;
          foreach($response['layer'] as $val){

            $xml_node_data = $xml->createElement("Data");
            $xml_node_data->setAttribute("id", $count++);
            $xml_node_datas->appendChild( $xml_node_data);

            $xml_node_type = $xml->createElement("type","list");
            $xml_node_data->appendChild( $xml_node_type);

            //Check thai country 
            if($response['country'] == "TH"){
              $string = "อำเภอ";
              if(strstr($val['district'],$string)){
                $district = $val['district'];
              }else{
                $district = "อำเภอ".$val['district'];
              }
            }else{
              $district = $val['district'];
            }

            $xml_node_title = $xml->createElement("title", $district);
            $xml_node_data->appendChild( $xml_node_title);

            $arg = array(
                          'pro' => $val['province'],
                          'dis' => $val['district']
                        );
            $xml_node_xml = $xml->createElement("xml", htmlentities($this->getNextURL("district", "tambon", $arg)));
            $xml_node_data->appendChild( $xml_node_xml);

          }
        }else{
          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );
        }

        echo $xml->saveXML();
    }

    public function getNextURL($currentLayer, $nextLayer, $arg){
      $page_url = 'http';
      if ($_SERVER['HTTPS'] == "on") {$pageURL .= "s";}
        $page_url .= "://";
      if ($_SERVER['SERVER_PORT'] != "80") {
        $page_url .= $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'];
      } else {
        $page_url .= $_SERVER['SERVER_NAME'];
      }
      $explode_key = explode("&key",$_SERVER['REQUEST_URI']);
      $explode_pro = explode("&pro",$explode_key[0]);
      $new_url = str_replace("filter=".$currentLayer, "filter=".$nextLayer, $explode_pro[0]);
      foreach($arg as $key=>$val){
        $uri[] = $key."=".urlencode($val);
      }
      $uri = implode("&", $uri);

      return $page_url.$new_url."&".$uri;
    }
  }


?>